package com.app.medicalcontrol.basis;

import android.animation.Animator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.app.medicalcontrol.R;
import com.app.medicalcontrol.adapter.MessageAdapter;
import com.app.medicalcontrol.bean.BasisBean;
import com.app.medicalcontrol.bean.MessageListBean;
import com.app.medicalcontrol.event.MessageEvent;
import com.app.medicalcontrol.util.AnimUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.loopj.android.http.RequestParams;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import my.ViewUtils;
import my.base.BaseFragment;
import my.http.HttpRestClient;
import my.http.MyHttpListener;

public class BasisFragment extends BaseFragment {

    protected Activity mContext;
    // LoadingDialog mLoadingDialog;
    KProgressHUD mLoadingDialog;

    private PopupWindow mPopupWindow;
    private AnimUtil animUtil;
    private BaseQuickAdapter adapter;

    private float bgAlpha = 1f;
    private boolean bright = false;

    private static final long DURATION = 500;
    private static final float START_ALPHA = 0.7f;
    private static final float END_ALPHA = 1f;

    @Override
    public void initConfig(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        mContext = getActivity();
        mLoadingDialog = KProgressHUD.create(mContext,
                KProgressHUD.Style.SPIN_INDETERMINATE).setSize(80, 80).setCancellable(true);
        EventBus.getDefault().register(this);

        mPopupWindow = new PopupWindow(mContext);
        animUtil = new AnimUtil();

        super.initConfig(savedInstanceState);
    }

    @Override
    public void setContentView(int layoutResID) {
        // TODO Auto-generated method stub
        super.setContentView(layoutResID);
        if (findViewById(R.id.main_view) != null) {
            findViewById(R.id.main_view).setOnClickListener(
                    new OnClickListener() {
                        public void onClick(View v) {
                            ViewUtils.hideInput(mContext, v);
                        }
                    });
        }
        if (findViewById(R.id.main_view2) != null) {
            findViewById(R.id.main_view2).setOnClickListener(
                    new OnClickListener() {
                        public void onClick(View v) {
                            ViewUtils.hideInput(mContext, v);
                        }
                    });
        }
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    public void showToast(String content) {
        try {
            Toast.makeText(getActivity(), content, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showToast(int resId) {
        try {
            Toast.makeText(getActivity(), resId, Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void initViews() {
        // TODO Auto-generated method stub
        // mLoadingDialog = new LoadingDialog(mContext);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        // TODO Auto-generated method stub

    }

    public void showProgress() {
        showLoadingDialog();
    }

    public void showLoading() {
        showLoadingDialog();
    }

    public void hideLoading() {
        hideLoadingDialog();
    }

    public void dismissProgress() {
        hideLoadingDialog();
    }

    public void showLoadingDialog() {
        mLoadingDialog.show();
    }

    public void hideLoadingDialog() {
        if (mLoadingDialog.isShowing())
            mLoadingDialog.dismiss();
    }

    public Fragment getRootFragment() {
        if (getParentFragment() == null) {
            return this;
        }
        Fragment fragment = getParentFragment();
        while (fragment.getParentFragment() != null) {
            fragment = getParentFragment();
        }
        return fragment;
    }

    public void onDataRefresh() {

    }

    @Subscribe
    public void onRefreshEvent(RefreshEvent event) {
//        showToast("认证结果"+(event.isDone));
        if (getActivity() == null) return;
        onDataRefresh();
    }

    public static class RefreshEvent {

    }

    public void setTitle(String titleStr) {
        TextView title = (TextView) findViewById(R.id.base_title_text);
        if (title == null) {
            return;
        }
        title.setVisibility(View.VISIBLE);
        title.setText(titleStr);
        findViewById(R.id.base_title_logo).setVisibility(View.GONE);
    }

    public void setTitleRightButton(int drawableRes, OnClickListener onClickListener) {
        if (findViewById(R.id.base_btn_right) == null)
            return;
        findViewById(R.id.base_btn_right).setOnClickListener(onClickListener);
        ((ImageView) findViewById(R.id.base_btn_right_icon))
                .setImageResource(drawableRes);
        findViewById(R.id.base_btn_right).setVisibility(
                drawableRes == 0 ? View.INVISIBLE : View.VISIBLE);
    }

    public void setTitleRightButton2(int drawableRes, OnClickListener onClickListener) {
        if (findViewById(R.id.base_btn_right2) == null)
            return;
        findViewById(R.id.base_btn_right2).setOnClickListener(onClickListener);
        ((ImageView) findViewById(R.id.base_btn_right_icon2))
                .setImageResource(drawableRes);
        findViewById(R.id.base_btn_right2).setVisibility(View.VISIBLE);
    }

    public void setTitleLeftButton(int drawableRes,
                                   OnClickListener onClickListener) {
        if (findViewById(R.id.base_btn_back) == null)
            return;
        findViewById(R.id.base_btn_back).setOnClickListener(onClickListener);
        ((ImageView) findViewById(R.id.base_btn_back_icon))
                .setImageResource(drawableRes);
        findViewById(R.id.base_btn_back).setVisibility(View.VISIBLE);
    }

    public void setTitleLeftButton(OnClickListener onClickListener) {
        if (findViewById(R.id.base_btn_back) == null)
            return;
        if (onClickListener == null) {
            onClickListener = new OnClickListener() {
                public void onClick(View v) {
                    finish();
                }
            };
        }
        findViewById(R.id.base_btn_back).setOnClickListener(onClickListener);
        findViewById(R.id.base_btn_back).setVisibility(View.VISIBLE);
    }


    public  void getMessageInfo(final View address) {
        showLoading();
        RequestParams params = new RequestParams();
        HttpRestClient.post(Constants.URL_MESSAGE_LIST, params, new MyHttpListener() {
            @Override
            public void onSuccess(int httpWhat, Object result) {
                MessageListBean listBean = (MessageListBean) result;
                if(listBean.getData().size()<1){
                    MessageListBean.MessageBean bean = new MessageListBean.MessageBean();
                    bean.setContent("暂无消息~");
                    List<MessageListBean.MessageBean> dataList = new ArrayList<>();
                    dataList.add(bean);
                    listBean.setData(dataList);
                }
                showPop(address,listBean);
                hideRedCircle();
            }

            @Override
            public void onFinish(int httpWhat) {
                hideLoading();
            }
        }, 0, MessageListBean.class);
    }

    public void showPop(View address,MessageListBean listBean) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.pop_recycler_view, null);
        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recy);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new MessageAdapter(R.layout.pop_text, listBean.getData());
        adapter.setEmptyView(LayoutInflater.from(mContext).inflate(R.layout.base_refresh_view,null));
        recyclerView.setAdapter(adapter);

        // 设置布局文件
        mPopupWindow.setContentView(view);
        // 为了避免部分机型不显示，我们需要重新设置一下宽高
        mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
//        mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setHeight(500);
        // 设置pop透明效果
        mPopupWindow.setBackgroundDrawable(new ColorDrawable(0x0000));
        // 设置pop出入动画
        mPopupWindow.setAnimationStyle(R.style.pop_add);
        // 设置pop获取焦点，如果为false点击返回按钮会退出当前Activity，如果pop中有Editor的话，focusable必须要为true
        mPopupWindow.setFocusable(true);
        // 设置pop可点击，为false点击事件无效，默认为true
        mPopupWindow.setTouchable(true);
        // 设置点击pop外侧消失，默认为false；在focusable为true时点击外侧始终消失
        mPopupWindow.setOutsideTouchable(true);
        // 相对于 + 号正下面，同时可以设置偏移量
        mPopupWindow.showAsDropDown(address, -100, 0);
        toggleBright();
    }

    public void toggleBright() {
        // 三个参数分别为：起始值 结束值 时长，那么整个动画回调过来的值就是从0.5f--1f的
        animUtil.setValueAnimator(START_ALPHA, END_ALPHA, DURATION);
        animUtil.addUpdateListener(new AnimUtil.UpdateListener() {
            @Override
            public void progress(float progress) {
                // 此处系统会根据上述三个值，计算每次回调的值是多少，我们根据这个值来改变透明度
                bgAlpha = bright ? progress : (START_ALPHA + END_ALPHA - progress);
//                backgroundAlpha(bgAlpha);
            }
        });
        animUtil.addEndListner(new AnimUtil.EndListener() {
            @Override
            public void endUpdate(Animator animator) {
                // 在一次动画结束的时候，翻转状态
                bright = !bright;
            }
        });
        animUtil.startAnimator();
    }

    public void showRedCircle() {
        ImageView redCircle = (ImageView) findViewById(R.id.iv_message);
        redCircle.setVisibility(View.VISIBLE);
    }

    public void hideRedCircle() {
        ImageView redCircle = (ImageView) findViewById(R.id.iv_message);
        redCircle.setVisibility(View.GONE);
    }

    //订阅方法，当接收到事件的时候，会调用该方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent messageEvent){
        Log.d("cylog","receive it");
        showRedCircle();
    }

}
